﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Collections.Generic;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using TarreOA.TarreOAModels;
using TarreOA.TarreOABLL;
using TarreOA.TarreOADAL;
using System.Data.SqlClient;

public partial class User_SendShortMessage : System.Web.UI.Page {

    private SectionServices sectionService = new SectionServices();
    private UserManager userManager = new UserManager();
    private SectionEmpMsgtbService sectionEmpMsgtbService = new SectionEmpMsgtbService();

    protected void Page_Load(object sender, EventArgs e) {
        if("section".Equals(this.sendTarget.SelectedValue)) {
            this.sectionPanel.Visible = true;
            this.someOnePanel.Visible = false;
            this.someGroupPanel.Visible = false;
            this.theOnePanel.Visible = false;
            this.sectionSendButton.Visible = true;
            this.sectionEmpSendButton.Visible = false;
            this.someGroupSendButton.Visible = false;
            this.theOneSendButton.Visible = false;
            fillSectionsShowLbx();
        } else if("someOne".Equals(this.sendTarget.SelectedValue)) {
            this.sectionPanel.Visible = false;
            this.someOnePanel.Visible = true;
            this.theOnePanel.Visible = false;
            this.someGroupPanel.Visible = false;
            this.sectionSendButton.Visible = false;
            this.sectionEmpSendButton.Visible = true;
            this.someGroupSendButton.Visible = false;
            this.theOneSendButton.Visible = false;
            sectionEmpTreeBind();
        } else if("someGroup".Equals(this.sendTarget.SelectedValue)) {
            this.someGroupPanel.Visible = true;
            this.sectionPanel.Visible = false;
            this.someOnePanel.Visible = false;
            this.theOnePanel.Visible = false;
            this.sectionSendButton.Visible = false;
            this.sectionEmpSendButton.Visible = false;
            this.someGroupSendButton.Visible = true;
            this.theOneSendButton.Visible = false;
        } else if("theOne".Equals(this.sendTarget.SelectedValue)) {
            this.theOnePanel.Visible = true;
            this.sectionPanel.Visible = false;
            this.someGroupPanel.Visible = false;
            this.someOnePanel.Visible = false;
            this.sectionSendButton.Visible = false;
            this.sectionEmpSendButton.Visible = false;
            this.someGroupSendButton.Visible = false;
            this.theOneSendButton.Visible = true;
            this.fillWillSelectOneLbx();
        }
        this.sectionEmpLtb.Attributes.Add("ondblclick", "moveSelectEmp('sectionEmpLtb','selectEmpLbx')");
        this.selectEmpLbx.Attributes.Add("ondbclick", "moveSelectEmp('selectEmpLbx','sectionEmpLtb')");
    }

    protected void fillSectionsShowLbx() {

        this.sectionShowLbx.Items.Clear();
        SectionServices sectionService = new SectionServices();
        foreach(Section section in sectionService.findAllSection()) {
            this.sectionShowLbx.Items.Add(new ListItem("   " + section.SectionName, section.SectionId.ToString()));
        }
    }

    //将部门信息绑定到树控件
    private void sectionEmpTreeBind() {
        this.secondSectionTree.Nodes.Clear();
        TreeNode rootNode = new TreeNode();
        rootNode.Text = "所有部门";
        rootNode.Value = "0";
        rootNode.SelectAction = TreeNodeSelectAction.Select;
        rootNode.ImageUrl = "~/images/Section.png";
        this.secondSectionTree.Nodes.Add(rootNode);
        foreach(Section section in sectionService.findByBaseSectionId(0)) {
            TreeNode node = new TreeNode();
            node.Text = section.SectionName;
            node.Value = section.SectionId.ToString();
            node.SelectAction = TreeNodeSelectAction.Select;
            node.ImageUrl = "~/images/Sections.png";
            rootNode.ChildNodes.Add(node);
            sectionEmpTreeFill(node, section.SectionId);
        }
        this.secondSectionTree.ExpandAll();
        this.fillWillSelectSectionEmp();
    }

    //部门信息递归填充
    private void sectionEmpTreeFill(TreeNode node, int bsid) {
        List<Section> list = sectionService.findByBaseSectionId(bsid);
        if(list.Count == 0) {
            return;
        } else {
            foreach(Section section in list) {
                TreeNode childNode = new TreeNode();
                childNode.Text = section.SectionName;
                childNode.Value = section.SectionId.ToString();
                childNode.ImageUrl = "~/images/Sections.png";
                childNode.SelectAction = TreeNodeSelectAction.Select;
                node.ChildNodes.Add(childNode);
                sectionEmpTreeFill(childNode, section.SectionId);
            }
        }
    }

    //将部门员工添加到预选人员列表中
    private void fillWillSelectSectionEmp() {
        this.sectionEmpLtb.Items.Clear();
        User curLoginUser = (User) Session["user"];
        int bsid = 0;
        if(this.secondSectionTree.SelectedNode != null) {
            bsid = int.Parse(this.secondSectionTree.SelectedNode.Value);
        }


        SqlConnection sqlConn = null;
        SqlCommand sqlCmd = null;
        SqlDataReader sqlDr = null;
        string state = "";
        try
        {
            sqlConn = SQLManager.GetConn();
            sqlConn.Open();
            if (bsid == 0)
                sqlCmd = new SqlCommand("select username,userid,loginname from usertb order by userid", sqlConn);
            else
                sqlCmd = new SqlCommand("select username,userid,loginname from usertb where [section]=" + bsid.ToString() + " order by userid", sqlConn);
            sqlDr = sqlCmd.ExecuteReader();
            while (sqlDr.Read())
            {
                state = "离线";
                if (!sqlDr["loginname"].ToString().Equals(curLoginUser.LoginName))
                {
                    if (OnlineList.getOnlineUsers()[sqlDr["loginname"].ToString()] != null)
                    {
                        state = "在线";
                    }
                    this.sectionEmpLtb.Items.Add(new ListItem(sqlDr["username"].ToString() + "[" + state + "]", sqlDr["userid"].ToString()));
                }
            }
        }
        catch (Exception ex)
        {
            Response.Write(ex.Message);
        }
        finally
        {
            if (sqlDr != null)
            {
                sqlDr.Close();
                sqlDr.Dispose();
            }
            if (sqlConn != null)
            {
                if (sqlConn.State == ConnectionState.Open)
                    sqlConn.Close();
                sqlConn.Dispose();
            }
        }


        //List<int> csids = sectionService.findAllChildSectionByBaseSectionId(bsid);
        //string state = "";
        //foreach(int i in csids) {
        //    foreach(User user in userManager.findBySectionId(i)) {
        //        state = "离线";
        //        if(OnlineList.getOnlineUsers()[user.LoginName] != null)
        //        {
        //            state = "在线";
        //        }
        //        //if (user.UserId != curLoginUser.UserId)
        //        //{
        //        this.sectionEmpLtb.Items.Add(new ListItem(user.UserName + "[" + state + "]", user.UserId.ToString()));
        //        //}
        //    }
        //}
    }

    protected void secondSectionTree_SelectedNodeChanged(object sender, EventArgs e) {
        fillWillSelectSectionEmp();
    }

    //将所有人员名单添加到指定通讯人列表框中
    protected void fillWillSelectOneLbx() {
        User curLoginUser = (User) Session["user"];
        this.willSelectOneLbx.Items.Clear();


        SqlConnection sqlConn = null;
        SqlCommand sqlCmd = null;
        SqlDataReader sqlDr = null;
        string state = "";
        try
        {
            sqlConn = SQLManager.GetConn();
            sqlConn.Open();
            sqlCmd = new SqlCommand("select username,userid from usertb order by userid", sqlConn);
            sqlDr = sqlCmd.ExecuteReader();
            while (sqlDr.Read())
            {
                state = "离线";
                if (!sqlDr["loginname"].ToString().Equals(curLoginUser.LoginName))
                {
                    if (OnlineList.getOnlineUsers()[sqlDr["loginname"].ToString()] != null)
                    {
                        state = "在线";
                    }
                    this.willSelectOneLbx.Items.Add(new ListItem(sqlDr["username"].ToString() + "[" + state + "]", sqlDr["userid"].ToString()));
                }
            }
        }
        catch (Exception ex)
        {
            Response.Write(ex.Message);
        }
        finally
        {
            if (sqlDr != null)
            {
                sqlDr.Close();
                sqlDr.Dispose();
            }
            if (sqlConn != null)
            {
                if (sqlConn.State == ConnectionState.Open)
                    sqlConn.Close();
                sqlConn.Dispose();
            }
        }
        
        
        //List<int> csids = sectionService.findAllChildSectionByBaseSectionId(0);
        //string state = "";
        //foreach(int csid in csids) {
        //    foreach(User user in userManager.findBySectionId(csid)) {
        //        state = "离线";
        //        if(user.UserId != curLoginUser.UserId) {
        //            if(OnlineList.getOnlineUsers()[user.LoginName] != null)
        //            {
        //                state = "在线";
        //            }
        //            this.willSelectOneLbx.Items.Add(new ListItem(user.UserName + "[" + state + "]", user.UserId.ToString()));
        //        }
        //    }
        //}
    }
    protected void sectionSendButton_Click(object sender, EventArgs e) {
        this.addMsgToSection();
    }
    protected void msgTimer_Tick(object sender, EventArgs e) {
        User curLoginUser = (User) Session["user"];
        if(Application[curLoginUser.LoginName + "Msg"] != null && "shortMessage".Equals(Application[curLoginUser.LoginName + "msg"].ToString())) {
            //ScriptManager.RegisterStartupScript(Page, this.GetType(), "msg", "if (confirm('您有新短消息,是否现在查看?')){window.open('ShortMessageShow.aspx?uln=" +
            //    curLoginUser.LoginName + "','');}", true);
            ScriptManager.RegisterStartupScript(Page, this.GetType(), "msg", "alert('♀您有新短消息,请到我的收件箱中查收♀')", true);
            Application.Remove(curLoginUser.LoginName + "Msg");
        }
    }
    protected void sectionEmpSendButton_Click(object sender, EventArgs e) {
        this.addMsgToSectionEmp(this.selectEmpLbx.ClientID);
    }

    //将发送消息保存以通知对方(针对人员集合)
    protected void addMsgToSectionEmp(string selectedEmpCollection) {
        List<User> sendTargetUsers = new List<User>();
        //string[] emps = Request[this.selectedEmpCollection.ClientID].Split(',');
        string[] emps = Request.Form.GetValues(selectedEmpCollection);
        for(int i = 0; i < emps.Length; i++) {
            int uid = int.Parse(emps[i]);
            sendTargetUsers.Add(userManager.findByUserId(uid));
        }
        string msgContent = this.msgContent.Text;
        User curLoginUser = (User) Session["user"];
        DateTime sendDateTime = DateTime.Now;
        bool state = false;
        foreach(User user in sendTargetUsers) {
            //Application[user.LoginName + "Msg"] = "shortMessage";
            int msg_id = sectionEmpMsgtbService.saveSectionEmpMsg(user.LoginName, curLoginUser.LoginName, msgContent, sendDateTime);
            if(msg_id > 0)
            {
                state = true;
            }
            MessageAwoke.Instance().AddToShortMsg(user.LoginName, msg_id);
        }
        if(state)
        {
            ScriptManager.RegisterClientScriptBlock(Page, GetType(), "", "alert('短信发送成功！');", true);
        }
        else
        {
            ScriptManager.RegisterClientScriptBlock(Page, GetType(), "", "alert('短信发送失败，请检查网络！');", true);
        }
    }

    //将发送消息保存以通知对方(针对部门集合)
    protected void addMsgToSection() {
        List<User> sendTargetUsers = new List<User>();
        string[] selectSections = Request[this.sendTargetSections.ClientID].Split(',');
        for(int i = 0; i < selectSections.Length; i++) {
            int sid = int.Parse(selectSections[i]);
            List<int> childSections = sectionService.findAllChildSectionByBaseSectionId(sid);
            foreach(int csid in childSections) {
                foreach(User user in userManager.findBySectionId(csid)) {
                    sendTargetUsers.Add(user);
                }
            }
        }
        string msgContent = this.msgContent.Text;
        User curLoginUser = (User) Session["user"];
        DateTime sendDateTime = DateTime.Now;
        foreach(User user in sendTargetUsers) {
            //Application[user.LoginName] = "shortMessage";
           int msgid = sectionEmpMsgtbService.saveSectionEmpMsg(user.LoginName, curLoginUser.LoginName, msgContent, sendDateTime);
           MessageAwoke.Instance().AddToShortMsg(user.LoginName, msgid);
        }
    }
    protected void theOneSendButton_Click(object sender, EventArgs e) {
        this.addMsgToSectionEmp(this.selectedLbx.ClientID);
    }
}
